package com.leyou.auth.controller;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.properties.JwtConstans;
import com.leyou.auth.properties.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.LyExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author linzx
 * @date 2020/3/29
 */

@RestController
@RequestMapping
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;
//    @Value("${leyou.token.name:LY_TOKEN}")
//    private String tokenName ;
//    @Value("${leyou.token.cookie-max-live-time-minute:30}")
//    private Integer cookieMaxLiveTime ;
    @Autowired
    private JwtProperties jwtProps;


    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username
            , @RequestParam("password") String password
            , HttpServletResponse response
            , HttpServletRequest request
            ){
        String token = authService.login(username,password);
        CookieUtils.setCookie(request,response,JwtConstans.TOKEN_NAME,
                token,jwtProps.getExpire() * 60 ,"UTF-8",true);

        return ResponseEntity.noContent().build();
    }

    /**
     *校验
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(
            @CookieValue(JwtConstans.TOKEN_NAME) String token ,
            HttpServletResponse response
            , HttpServletRequest request
    ) {

        UserInfo userInfo = authService.verify(token);
        try {
            String token1 = JwtUtils.generateToken(userInfo, jwtProps.getPrivateKey(), jwtProps.getExpire() * 60);
            CookieUtils.setCookie(request,response,JwtConstans.TOKEN_NAME,
                    token,jwtProps.getExpire() * 60 ,"UTF-8",true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnums.CREATE_TOKEN_ERROR);
        }
        return ResponseEntity.ok(userInfo);
    }


}
